﻿Imports System.Xml.Serialization

Namespace Commands

    Public Class GetSharedItemFiles
        Inherits Framework.Net.CommandBase

        Private Const mRequestCode As String = "GetSharedItemFiles"
        Private Const mReplyCode As String = "GetSharedItemFilesReply"

        Public Sub New()
            MyBase.New(mRequestCode, mReplyCode)
        End Sub

        Public Class Request
            Public SharedItemId As Integer
        End Class
        Public Class Reply
            Public Files As Generic.List(Of Entities.SharedItemFile)
        End Class

        Public Shared Function Execute(ByVal node As Framework.Net.Node, ByVal sharedItemId As Integer) As Generic.List(Of Entities.SharedItemFile)
            Dim clsRequest As New Request
            clsRequest.SharedItemId = sharedItemId

            Dim clsMessage As Framework.Net.MessageBlock = node.SendCommandMessage(mRequestCode, Framework.Serialization.ToXmlBytes(clsRequest))
            Dim clsReply As Reply = Framework.Serialization.FromXmlBytes(Of Reply)(clsMessage.Message)
            Return clsReply.Files
        End Function

        Public Overrides Sub HandleReply(ByVal envelope As Framework.Net.MessageEnvelope)
            Throw New NotImplementedException
        End Sub

        Public Overrides Sub HandleRequest(ByVal envelope As Framework.Net.MessageEnvelope)
            Dim clsRequest As Request = Framework.Serialization.FromXmlBytes(Of Request)(envelope.Message.Message)

            Dim clsReply As New Reply
            Dim clsItem As Entities.SharedItem = EntityHandlers.SharedItems.GetById(clsRequest.SharedItemId)
            If clsItem IsNot Nothing Then
                Dim clsShare As Entities.Share = EntityHandlers.Shares.GetById(clsItem.ShareId)
                If clsShare IsNot Nothing Then
                    If envelope.Node.BuddyKeyMaster.IsGranted(clsShare) Then
                        clsReply.Files = EntityHandlers.SharedItemsFiles.GetAllBySharedItemId(clsRequest.SharedItemId)
                    End If
                End If
            End If
            envelope.Node.SendReplyCommandMessageAsync(envelope, mReplyCode, Framework.Serialization.ToXmlBytes(clsReply))
        End Sub
    End Class
End Namespace
